package bug.hibernate;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.orm.hibernate3.HibernateInterceptor;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by IntelliJ IDEA.
 * User: AJD
 * Date: 2/26/11
 * Time: 11:43 PM
 * To change this template use File | Settings | File Templates.
 */
@Aspect
public class HibernateInterceptorAdvice {

     @Autowired
     private HibernateInterceptor hibernateInterceptor;

     @Around("execution(* bug.dao.hibernate.getAll*(..))")
     public Object interceptCall(ProceedingJoinPoint joinPoint) throws Throwable {

         System.out.println("Call intercepted...");

         ProxyFactory proxyFactory = new ProxyFactory(joinPoint.getTarget());
         proxyFactory.addAdvice(hibernateInterceptor);

         Class [] classArray = new Class[joinPoint.getArgs().length];
         for (int i = 0; i < classArray.length; i++)
             classArray[i] = joinPoint.getArgs()[i].getClass();

         return
             proxyFactory
                 .getProxy()
                 .getClass()
                 .getDeclaredMethod(joinPoint.getSignature().getName(), classArray)
                 .invoke(proxyFactory.getProxy(), joinPoint.getArgs());

     }

}
